<template>
  <div class="followAdd" v-loading="detailInfoShow">
    <!-- 筛选按钮 -->
    <div
      class="search-button"
      v-if="pageType !== 'detail' && pageType !== 'check'"
    >
      <!-- <el-button
        v-if="pageType !== 'detail' && pageType !== 'check'"
        class="btn save"
        @click="handleEndOperation()"
        ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
        >完结</el-button
      > -->
      <el-button class="btn back" @click="handleBack"
        ><el-icon class="icon" color="#fff"> <Back /> </el-icon>返回</el-button
      >
    </div>
    <div class="task-box">
      <div class="task transform-down">
        <template v-for="(item, index) in taskList" :key="index">
          <div
            v-if="item.label !== '设备到货清单-销售'"
            class="task-item"
            :class="currentTask === item.value ? 'task-current' : ''"
            @click="handleTaskClick(item)"
          >
            {{ item.label }}
          </div>
        </template>
      </div>
      <!-- <div class="search-button" style="top: 30px">
        <el-button
          v-if="pageType !== 'detail' && pageType !== 'check'"
          class="btn save"
          style="width: 120px"
          @click="handleAddSave(followFormRef)"
          ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
          >保存当前任务</el-button
        >
      </div> -->
    </div>
    <el-collapse v-model="activeNames">
      <!-- 基础信息 -->
      <el-collapse-item
        name="1"
        class="transform-down"
        v-if="!contactAddShow && !saleAddShow"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">任务信息</span>
        </template>
        <div class="follow-info">
          <el-form
            :model="followForm"
            ref="followFormRef"
            :rules="queryRules"
            label-width="120px"
            v-enterToNext
            :disabled="
              pageType === 'detail' ||
              ['待执行', '已完成'].includes(followForm.taskImplStatusName)
            "
          >
            <template v-if="pageType !== 'detail'">
              <el-row>
                <!-- <el-col :span="6">
                  <el-form-item label="任务名称：">
                    <el-input
                      style="width: 268px"
                      v-model="followForm.proTaskName"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                      disabled
                    />
                  </el-form-item>
                </el-col> -->
                <!-- <el-col :span="6">
                  <el-form-item label="分配时间：">
                    <el-date-picker
                      value-format="YYYY-MM-DD HH:mm:ss"
                      v-model="followForm.createTime"
                      class="search-input"
                      type="datetime"
                      placeholder="请选择"
                      disabled
                    />
                  </el-form-item>
                </el-col> -->
                <el-col :span="6">
                <el-form-item label="选择工程师：" prop="allotRelList">
                  <el-select
                  filterable
                    style="height: 100%"
                    v-model="followForm.allotRelList"
                    multiple
                    placeholder="请选择"
                    clearable
                    class="search-input"
                  >
                    <el-option key="0" label="" value="" disabled>
                      <span style="float: left; color: #8492a6">人员姓名</span>
                      <span style="margin: 0 80px 0 50px; color: #8492a6"
                        >联系方式</span
                      >
                      <span
                        style="
                          margin: 0 100px 0 0px;
                          color: #8492a6;
                          font-size: 13px;
                        "
                        >职位</span
                      >
                      <span style="color: #8492a6; font-size: 13px">部门</span>
                    </el-option>
                    <el-option
                      v-for="item in userList"
                      :key="item.userId"
                      :label="item.nickName"
                      :value="item.userId"
                    >
                      <span
                        style="display: inline-block; width: 80px; float: left"
                        >{{ item.nickName }}</span
                      >
                      <span
                        style="
                          display: inline-block;
                          width: 125px;
                          margin: 0 15px 0 23px;
                          color: #8492a6;
                          white-space: nowrap;
                          overflow: hidden;
                          text-overflow: ellipsis;
                        "
                        >{{ item.phonenumber ? item.phonenumber : "--" }}</span
                      >
                      <span
                        style="
                          display: inline-block;
                          width: 125px;
                          font-size: 13px;
                          margin: 0 0px 0 0px;
                          transform: translateY(-11px);
                          color: #8492a6;
                        "
                      >
                        {{ item.postName ? item.postName : "--" }}
                      </span>
                      <span
                        style="
                          display: inline-block;
                          margin: 0 0px 0 0px;
                          font-size: 13px;
                          transform: translateY(-11px);
                          color: #8492a6;
                        "
                      >
                        {{ item.fullDeptName ? item.fullDeptName : "--" }}
                      </span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
                <el-col :span="6">
                  <el-form-item label="计划开始时间：" prop="startTime">
                    <el-date-picker
                      value-format="YYYY-MM-DD HH:mm:ss"
                      v-model="followForm.startTime"
                      class="search-input"
                      type="datetime"
                      placeholder="请选择"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="距离开始天数：">
                    <el-input
                      style="width: 268px"
                      v-model="followForm.startTimeNum"
                      placeholder="自动获取"
                      clearable
                      disabled
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
              <!-- </el-row>
              <el-row> -->
                <el-col :span="6">
                  <el-form-item label="计划结束时间：" prop="endTime">
                    <el-date-picker
                      value-format="YYYY-MM-DD HH:mm:ss"
                      v-model="followForm.endTime"
                      class="search-input"
                      type="datetime"
                      placeholder="请选择"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="距离结束天数：">
                    <el-input
                      style="width: 268px"
                      v-model="followForm.endTimeNum"
                      placeholder="自动获取"
                      clearable
                      disabled
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="预估工时：" prop="estimatedWorkHours">
                    <el-input
                      style="width: 268px"
                      v-model="followForm.estimatedWorkHours"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="备注" prop="remark">
                    <el-input
                      style="width: 268px"
                      v-model="followForm.remark"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
              <!-- </el-row>
              <el-row> -->
                <el-col
                  :span="6"
                  v-if="[0, 2, 3, 5, 6, 7].includes(currentTask)"
                >
                  <el-form-item label="实际工时：" prop="actualHour">
                    <el-input
                      style="width: 268px"
                      v-model="followForm.actualHour"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                      maxlength="10"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="[0, 2, 3, 5, 6, 7].includes(currentTask)">
                <el-col :span="6">
                  <el-form-item label="交付文件：" prop="suppFileInfoVos">
                    <Upload
                      :fileList="
                        followForm.ywImplProInfoReqVos[0].suppFileInfoVos
                      "
                      :limit="10"
                      limitation="templatelimitation"
                      accept=".doc,.docx"
                      :isFull="true"
                      :isCanDelete="
                        pageType == 'detail' ||
                        !['进行中'].includes(followForm.taskImplStatusName)
                          ? false
                          : true
                      "
                      :disabled="
                        pageType == 'detail' ||
                        !['进行中'].includes(followForm.taskImplStatusName)
                      "
                      :showButton="true"
                      @success="(result) => uploadSuccess(result)"
                      @deleteFile="(result) => uploadRemove(result)"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
            <template v-if="pageType === 'detail'">
              <el-row>
                <el-col :span="6">
                  <el-form-item label="执行人：">
                    <el-input
                      style="width: 268px"
                      v-model="followForm.executor"
                      placeholder="--"
                      clearable
                      class="search-input"
                      disabled
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="分配人：">
                    <el-input
                      style="width: 268px"
                      v-model="followForm.assigner"
                      placeholder="--"
                      clearable
                      class="search-input"
                      disabled
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="分配时间：">
                    <el-input
                      style="width: 268px"
                      v-model="followForm.createTime"
                      placeholder="--"
                      clearable
                      class="search-input"
                      disabled
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="计划开始时间：">
                    <el-input
                      style="width: 268px"
                      v-model="followForm.startTime"
                      placeholder="--"
                      clearable
                      class="search-input"
                      disabled
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="计划结束时间：">
                    <el-input
                      style="width: 268px"
                      v-model="followForm.endTime"
                      placeholder="--"
                      clearable
                      class="search-input"
                      disabled
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="实际开始时间：">
                    <el-input
                      style="width: 268px"
                      v-model="followForm.actualStartTime"
                      placeholder="--"
                      clearable
                      class="search-input"
                      disabled
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="实际结束时间：">
                    <el-input
                      style="width: 268px"
                      v-model="followForm.finishTime"
                      placeholder="--"
                      clearable
                      class="search-input"
                      disabled
                    />
                  </el-form-item>
                </el-col>
                <el-col
                  :span="6"
                  v-if="[0, 2, 3, 5, 6, 7].includes(currentTask)"
                >
                  <el-form-item label="实际工时：">
                    <el-input
                      style="width: 268px"
                      v-model="followForm.actualHour"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                      maxlength="10"
                    />
                  </el-form-item>
                </el-col>
                <el-col
                  :span="6"
                  v-if="[0, 2, 3, 5, 6, 7].includes(currentTask)"
                >
                  <el-form-item label="交付文件：">
                    <Upload
                      :fileList="
                        followForm.ywImplProInfoReqVos[0].suppFileInfoVos
                      "
                      :limit="10"
                      limitation="templatelimitation"
                      accept=".doc,.docx"
                      :isFull="true"
                      :isCanDelete="
                        pageType == 'detail' ||
                        !['进行中'].includes(followForm.taskImplStatusName)
                          ? false
                          : true
                      "
                      :disabled="
                        pageType == 'detail' ||
                        !['进行中'].includes(followForm.taskImplStatusName)
                      "
                      :showButton="false"
                      @success="(result) => uploadSuccess(result)"
                      @deleteFile="(result) => uploadRemove(result)"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="备注：">
                    <el-input
                      maxlength="2000"
                      style="width: 268px"
                      v-model="followForm.remark"
                      placeholder="--"
                      clearable
                      class="search-input"
                      disabled
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="退回原因：">
                    <el-input
                      style="width: 268px"
                      v-model="followForm.returnReasons"
                      placeholder="--"
                      clearable
                      class="search-input"
                      disabled
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
          </el-form>
          <!-- {{ followForm.taskImplStatusName }} -->
          <div
            class="footer-button"
            v-if="pageType !== 'detail' && currentTask !== null"
          >
            <!-- v-if="form.implStatus === 0" -->
            <el-button
              v-if="false"
              v-preventReClick
              size="mini"
              type="primary"
              @click="handleTaskOperate(1, followFormRef)"
            >
              退回当前任务
            </el-button>
            <!-- v-if="form.implStatus === 0" -->
            <el-button
              v-if="false"
              v-preventReClick
              size="mini"
              type="primary"
              @click="handleTaskOperate(2, followFormRef)"
            >
              开始当前任务
            </el-button>
            <!-- v-if="form.implStatus === 1" -->
            <el-button
              v-if="['进行中'].includes(followForm.taskImplStatusName)"
              v-preventReClick
              size="mini"
              type="primary"
              @click="handleTaskOperate(3, followFormRef)"
            >
              保存当前任务
            </el-button>
          </div>
        </div>
      </el-collapse-item>
      <el-collapse-item
        name="2"
        style="position: relative"
        v-if="saleAddShow && !contactAddShow"
        class="transform-up"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">添加现场勘察任务明细</span>
        </template>
        <div class="follow-info">
          <el-form
            :model="saleForm"
            ref="saleFormRef"
            :rules="querySaleRules"
            label-width="120px"
            v-enterToNext
          >
            <el-row>
              <el-col :span="6">
                <el-form-item label="实时工时：" prop="actualHour">
                  <el-input
                    maxlength="10"
                    v-model="saleForm.actualHour"
                    placeholder="请输入"
                    clearable
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="物业名称：" prop="propertyName">
                  <el-input
                    maxlength="10"
                    v-model="saleForm.propertyName"
                    placeholder="请输入"
                    clearable
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="所属派出所：" prop="policeOffice">
                  <el-input
                    maxlength="10"
                    v-model="saleForm.policeOffice"
                    placeholder="请输入"
                    clearable
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="物业联系方式：" prop="propertyWay">
                  <el-input
                    maxlength="11"
                    v-model="saleForm.propertyWay"
                    placeholder="请输入"
                    clearable
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="民警联系方式：" prop="policeWay">
                  <el-input
                    v-model="saleForm.policeWay"
                    placeholder="请输入"
                    clearable
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="省市区：" prop="cityId" label-width="110">
                  <el-select
                    filterable
                    style="width: 93px"
                    v-model="saleForm.provinceId"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                    @change="handleProvince('province', saleForm.provinceId)"
                  >
                    <el-option
                      v-for="dict in provinceList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                  <el-select
                    filterable
                    style="width: 93px; margin: 0 5px"
                    v-model="saleForm.cityId"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                    @change="handleProvince('city', saleForm.cityId)"
                  >
                    <el-option
                      v-for="dict in cityList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                  <el-select
                    filterable
                    style="width: 93px"
                    v-model="saleForm.zoneId"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                    @change="handleProvince('area', saleForm.zoneId)"
                  >
                    <el-option
                      v-for="dict in areaList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="详细地址：" prop="detailAdd">
                  <el-input
                    maxlength="30"
                    style="width: 100%"
                    v-model="saleForm.detailAdd"
                    placeholder="请输入"
                    clearable
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="点位名称" prop="pointAdd">
                  <el-input
                    maxlength="10"
                    v-model="saleForm.pointAdd"
                    placeholder="请输入"
                    clearable
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="物业租赁合同：">
                  <Upload
                    :fileList="saleForm.suppFileInfoVos7"
                    :limit="10"
                    limitation="templatelimitation"
                    accept=".doc,.docx"
                    :isFull="true"
                    :isCanDelete="pageType == 'detail' ? false : true"
                    :disabled="pageType == 'detail'"
                    :showButton="true"
                    @success="(result) => uploadSuccess(result, 7)"
                    @deleteFile="(result) => uploadRemove(result, 7)"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="现场实地照片：">
                  <Upload
                    :fileList="saleForm.suppFileInfoVos1"
                    :limit="10"
                    limitation="templatelimitation"
                    accept=".doc,.docx"
                    :isFull="true"
                    :isCanDelete="pageType == 'detail' ? false : true"
                    :disabled="pageType == 'detail'"
                    :showButton="true"
                    @success="(result) => uploadSuccess(result, 1)"
                    @deleteFile="(result) => uploadRemove(result, 1)"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="外包用工合同：">
                  <Upload
                    :fileList="saleForm.suppFileInfoVos2"
                    :limit="10"
                    limitation="templatelimitation"
                    accept=".doc,.docx"
                    :isFull="true"
                    :isCanDelete="pageType == 'detail' ? false : true"
                    :disabled="pageType == 'detail'"
                    :showButton="true"
                    @success="(result) => uploadSuccess(result, 2)"
                    @deleteFile="(result) => uploadRemove(result, 2)"
                  />
                </el-form-item>
              </el-col>
              <!-- <el-col :span="6">
                <el-form-item label="设备名称：" prop="materialId">
                  <el-select
                    v-model="saleForm.materialId"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                    @change="handleDevice"
                  >
                    <el-option
                      v-for="dict in deviceList"
                      :key="dict.materialId"
                      :label="dict.saleName"
                      :value="dict.materialId"
                    />
                  </el-select>
                </el-form-item>
              </el-col> -->
            </el-row>
          </el-form>
        </div>
      </el-collapse-item>
      <!-- 销售清单明细 -->
      <el-collapse-item
        name="3"
        style="position: relative"
        v-show="!contactAddShow && currentTask === 1"
      >
        <!-- class="transform-down" -->
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">现场勘察任务明细</span>
          <div
            v-if="
              pageType !== 'detail' &&
              !saleAddShow &&
              pageType !== 'check' &&
              ['进行中'].includes(followForm.taskImplStatusName)
            "
            class="nofixed-search-button button-position"
          >
            <el-button class="btn add" @click.stop="handleSaleOperate"
              ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
              >添加</el-button
            >
          </div>
          <div
            class="nofixed-search-button button-position"
            v-else
            v-if="
              pageType !== 'detail' &&
              pageType !== 'check' &&
              ['进行中'].includes(followForm.taskImplStatusName)
            "
          >
            <el-button class="btn add" @click.stop="handleSaleAdd(saleFormRef)"
              ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
              >添加</el-button
            >
            <el-button class="btn direction" @click.stop="handleSaleBack"
              ><el-icon class="icon" color="#fff"> <ArrowUp /> </el-icon
              >关闭</el-button
            >
          </div>
        </template>
        <div class="contact-info">
          <!-- 表格数据 -->
          <el-table
            :data="followForm.ywImplProInfoReqVos"
            border
            :height="
              pageType === 'detail'
                ? '100%'
                : contactAddShow
                ? '180px'
                : '180px'
            "
            :header-cell-style="{ 'text-align': 'center' }"
          >
            <!-- 操作模式 -->
            <el-table-column
              label="操作"
              align="center"
              :show-overflow-tooltip="true"
              width="100px"
              v-if="
                pageType !== 'detail' &&
                ['进行中'].includes(followForm.taskImplStatusName)
              "
            >
              <!-- v-if="!operateType" -->
              <template #default="{ row, $index }">
                <div class="table-operate">
                  <img
                    src="@/assets/icons/images/edit.png"
                    class="table-icon"
                    title="编辑"
                    @click="handleOperateSec('edit', row, $index)"
                  />
                  <img
                    src="@/assets/icons/images/delete.png"
                    class="table-icon"
                    title="删除"
                    @click="handleOperateSec('delete', row, $index)"
                  />
                </div> </template
            ></el-table-column>
            <el-table-column
              label="实时工时"
              prop="actualHour"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="物业名称"
              prop="propertyName"
              :show-overflow-tooltip="true"
              min-width="160"
            ></el-table-column>
            <el-table-column
              label="所属派出所"
              prop="policeOffice"
              :show-overflow-tooltip="true"
              min-width="160"
            >
            </el-table-column>
            <el-table-column
              label="物业联系方式"
              prop="propertyWay"
              :show-overflow-tooltip="true"
              min-width="160"
            >
            </el-table-column>
            <el-table-column
              label="物业租赁合同"
              prop="suppFileInfoVos7"
              :show-overflow-tooltip="true"
              min-width="160"
            >
              <template #default="{ row }">
                <span
                  v-for="(item, index) in row.suppFileInfoVos7"
                  :key="index"
                  @click="handleFileClick(item)"
                  class="fileText"
                  >{{ item.name
                  }}<span
                    style="color: #000"
                    v-if="index + 1 !== row.suppFileInfoVos7.length"
                    >，</span
                  ></span
                >
              </template>
            </el-table-column>
            <el-table-column
              label="民警联系方式"
              prop="policeWay"
              :show-overflow-tooltip="true"
              min-width="160"
            ></el-table-column>
            <el-table-column
              label="现场实地照片"
              prop="suppFileInfoVos1"
              :show-overflow-tooltip="true"
              min-width="160"
            >
              <template #default="{ row }">
                <span
                  v-for="(item, index) in row.suppFileInfoVos1"
                  :key="index"
                  @click="handleFileClick(item)"
                  class="fileText"
                  >{{ item.name
                  }}<span
                    style="color: #000"
                    v-if="index + 1 !== row.suppFileInfoVos1.length"
                    >，</span
                  ></span
                >
                <!-- <span v-if="row.suppFileInfoVos7.length !== index+1">，</span> -->
              </template>
            </el-table-column>
            <el-table-column
              label="外包用工合同"
              prop="suppFileInfoVos2"
              :show-overflow-tooltip="true"
              min-width="160"
            >
              <template #default="{ row }">
                <span
                  v-for="(item, index) in row.suppFileInfoVos2"
                  :key="index"
                  @click="handleFileClick(item)"
                  class="fileText"
                  >{{ item.name
                  }}<span
                    style="color: #000"
                    v-if="index + 1 !== row.suppFileInfoVos2.length"
                    >，</span
                  ></span
                >
                <!-- <span v-if="row.suppFileInfoVos7.length !== index">，</span> -->
              </template>
            </el-table-column>
            <el-table-column
              label="选择省市区"
              prop=""
              :show-overflow-tooltip="true"
              min-width="160"
            >
              <template #default="scope">
                {{ scope.row.provinceName }}{{ scope.row.cityName
                }}{{ scope.row.zoneName }}
              </template>
            </el-table-column>
            <el-table-column
              label="详细地址"
              prop="detailAdd"
              :show-overflow-tooltip="true"
              min-width="160"
            />

            <el-table-column
              label="点位名称"
              prop="pointAdd"
              :show-overflow-tooltip="true"
              min-width="160"
            />
          </el-table>
        </div>
      </el-collapse-item>
      <!-- 添加现场安装/调试任务明细 -->
      <el-collapse-item
        name="4"
        style="position: relative"
        v-if="contactAddShow && !saleAddShow"
        class="transform-up"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">添加现场安装/调试任务明细</span>
        </template>
        <div class="follow-info">
          <el-form
            :model="saleForm"
            ref="contactFormRef"
            :rules="queryContactRules"
            label-width="120px"
            v-enterToNext
          >
            <el-row>
              <el-col :span="6">
                <el-form-item label="实时工时：" prop="actualHour">
                  <el-input
                    maxlength="10"
                    v-model="saleForm.actualHour"
                    placeholder="请输入"
                    clearable
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="选择防区：" prop="armedzoneId">
                  <el-select
                    v-model="saleForm.armedzoneId"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                    @change="handleDefenseChange"
                  >
                    <el-option
                      v-for="dict in defenseList"
                      :key="dict.id"
                      :label="dict.armedzoneName"
                      :value="dict.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="设备名称：" label-width="150" prop="deviceId">
                  <!--  -->
                  <!-- v-model="saleForm.deviceName" -->
                  <el-select 
                    v-model="saleForm.deviceId"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                    @change="handleDeviceChange"
                  >
                    <el-option
                      v-for="dict in deviceList"
                      :key="dict.id"
                      :label="dict.armedzoneName"
                      :value="dict.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="添加时间：" prop="createTime">
                  <el-input
                    v-model="saleForm.createTime"
                    placeholder="系统自动获取"
                    clearable
                    class="search-input"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="设备型号：">
                  <el-input
                    disabled
                    v-model="saleForm.deviceModel"
                    placeholder="自动获取"
                    clearable
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="设备类型：">
                  <el-select
                    disabled
                    v-model="saleForm.deviceType"
                    placeholder="自动获取"
                    clearable
                    class="search-input"
                    @change="handledeviceTypeChange"
                  >
                    <el-option
                      v-for="dict in deviceTypeList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="生产厂家："
                  label-width="150"
                >
                  <el-input
                    disabled
                    maxlength="10"
                    v-model="saleForm.manufacturer"
                    placeholder="自动获取"
                    clearable
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="安装方式：">
                  <el-input
                    disabled
                    maxlength="10"
                    v-model="saleForm.installType"
                    placeholder="自动获取"
                    clearable
                    class="search-input"
                  />
                </el-form-item> </el-col
              ><el-col :span="6">
                <el-form-item label="设备ID：">
                  <el-input
                    disabled
                    maxlength="20"
                    v-model="saleForm.deviceUuid"
                    placeholder="自动获取"
                    clearable
                    class="search-input"
                  />
                </el-form-item> </el-col
              ><el-col :span="6">
                <el-form-item label="SIM卡信息：" prop="simCard">
                  <el-input
                    maxlength="30"
                    v-model="saleForm.simCard"
                    placeholder="请输入"
                    clearable
                    class="search-input"
                  />
                </el-form-item> </el-col
              ><el-col :span="6">
                <el-form-item
                  label="路由器品牌型号："
                  prop="routBrand"
                  label-width="150"
                >
                  <el-input
                    maxlength="30"
                    v-model="saleForm.routBrand"
                    placeholder="请输入"
                    clearable
                    class="search-input"
                  />
                </el-form-item> </el-col
              ><el-col :span="6">
                <el-form-item label="IP地址：">
                  <el-input
                    maxlength="30"
                    disabled
                    v-model="saleForm.ipAddress"
                    placeholder="自动获取"
                    clearable
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="配件清单表：" prop="suppFileInfoVos3">
                  <Upload
                    :fileList="saleForm.suppFileInfoVos3"
                    :limit="10"
                    limitation="templatelimitation"
                    accept=".doc,.docx"
                    :isFull="true"
                    :isCanDelete="pageType == 'detail' ? false : true"
                    :disabled="pageType == 'detail'"
                    :showButton="true"
                    @success="(result) => uploadSuccess(result, 3)"
                    @deleteFile="(result) => uploadRemove(result, 3)"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="用电协议：" prop="suppFileInfoVos4">
                  <Upload
                    :fileList="saleForm.suppFileInfoVos4"
                    :limit="10"
                    limitation="templatelimitation"
                    accept=".doc,.docx"
                    :isFull="true"
                    :isCanDelete="pageType == 'detail' ? false : true"
                    :disabled="pageType == 'detail'"
                    :showButton="true"
                    @success="(result) => uploadSuccess(result, 4)"
                    @deleteFile="(result) => uploadRemove(result, 4)"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="现场完成照片："
                  label-width="150"
                  prop="suppFileInfoVos5"
                >
                  <Upload
                    :fileList="saleForm.suppFileInfoVos5"
                    :limit="10"
                    limitation="templatelimitation"
                    accept=".doc,.docx"
                    :isFull="true"
                    :isCanDelete="pageType == 'detail' ? false : true"
                    :disabled="pageType == 'detail'"
                    :showButton="true"
                    @success="(result) => uploadSuccess(result, 5)"
                    @deleteFile="(result) => uploadRemove(result, 5)"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="现场设备照片：" prop="suppFileInfoVos6">
                  <Upload
                    :fileList="saleForm.suppFileInfoVos6"
                    :limit="10"
                    limitation="templatelimitation"
                    accept=".doc,.docx"
                    :isFull="true"
                    :isCanDelete="pageType == 'detail' ? false : true"
                    :disabled="pageType == 'detail'"
                    :showButton="true"
                    @success="(result) => uploadSuccess(result, 6)"
                    @deleteFile="(result) => uploadRemove(result, 6)"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-collapse-item>
      <!-- 现场安装/调试任务明细 -->
      <el-collapse-item
        name="5"
        style="position: relative; margin-top: 20px"
        v-show="!saleAddShow && currentTask === 4"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">现场安装/调试任务明细</span>
          <div
            v-if="
              pageType !== 'check' &&
              pageType !== 'detail' &&
              !contactAddShow &&
              ['进行中'].includes(followForm.taskImplStatusName)
            "
            class="nofixed-search-button button-position"
          >
            <el-button class="btn add" @click.stop="handleContactOperate"
              ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
              >添加</el-button
            >
          </div>
          <div
            class="nofixed-search-button button-position"
            v-else
            v-if="
              pageType !== 'check' &&
              pageType !== 'detail' &&
              ['进行中'].includes(followForm.taskImplStatusName)
            "
          >
            <el-button
              class="btn add"
              @click.stop="handleSaleAdd(contactFormRef)"
              ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
              >添加</el-button
            >
            <el-button class="btn direction" @click.stop="handleProjectBack"
              ><el-icon class="icon" color="#fff"> <ArrowUp /> </el-icon
              >关闭</el-button
            >
          </div>
        </template>
        <div class="contact-info">
          <!-- 表格数据 -->
          <el-table
            :data="followForm.ywImplProInfoReqVos"
            border
            :height="
              pageType === 'detail'
                ? '100%'
                : contactAddShow
                ? '180px'
                : '180px'
            "
            :header-cell-style="{ 'text-align': 'center' }"
          >
            <!-- 操作模式 -->
            <el-table-column
              label="操作"
              align="center"
              :show-overflow-tooltip="true"
              width="100px"
              v-if="
                pageType !== 'detail' &&
                ['进行中'].includes(followForm.taskImplStatusName)
              "
            >
              <!-- v-if="!operateType" -->
              <template #default="{ row, $index }">
                <div class="table-operate">
                  <img
                    src="@/assets/icons/images/edit.png"
                    class="table-icon"
                    title="编辑"
                    @click="handleOperate('edit', row, $index)"
                  />
                  <img
                    src="@/assets/icons/images/delete.png"
                    class="table-icon"
                    title="删除"
                    @click="handleOperate('delete', row, $index)"
                  />
                </div> </template
            ></el-table-column>
            <el-table-column
              label="实时工时"
              prop="actualHour"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="选择防区"
              prop="armedzoneName"
              :show-overflow-tooltip="true"
              min-width="160"
            ></el-table-column>
            <el-table-column
              label="设备名称"
              prop="deviceName"
              :show-overflow-tooltip="true"
              min-width="160"
            >
            </el-table-column>
            <el-table-column
              label="添加时间"
              prop="createTime"
              :show-overflow-tooltip="true"
              min-width="160"
            >
            </el-table-column>
            <el-table-column
              label="设备型号"
              prop="deviceModel"
              :show-overflow-tooltip="true"
              min-width="160"
            ></el-table-column>
            <el-table-column
              label="设备类型"
              prop="deviceTypeName"
              :show-overflow-tooltip="true"
              min-width="160"
            ></el-table-column>
            <el-table-column
              label="生产厂家"
              prop="manufacturer"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="安装方式"
              prop="installType"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="设备ID"
              prop="deviceUuid"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="SIM卡信息"
              prop="simCard"
              :show-overflow-tooltip="true"
              min-width="160"
            />

            <el-table-column
              label="路由器品牌型号"
              prop="routBrand"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="IP地址"
              prop="ipAddress"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="配件清单表"
              prop="remarks"
              :show-overflow-tooltip="true"
              min-width="160"
            >
              <template #default="{ row }">
                <span
                  v-for="(item, index) in row.suppFileInfoVos3"
                  :key="index"
                  @click="handleFileClick(item)"
                  class="fileText"
                  >{{ item.name
                  }}<span
                    style="color: #000"
                    v-if="index + 1 !== row.suppFileInfoVos3.length"
                    >，</span
                  ></span
                >
                <!-- <span v-if="row.suppFileInfoVos7.length !== index">，</span> -->
              </template>
            </el-table-column>
            <el-table-column
              label="用电协议"
              prop="remarks"
              :show-overflow-tooltip="true"
              min-width="160"
            >
              <template #default="{ row }">
                <span
                  v-for="(item, index) in row.suppFileInfoVos4"
                  :key="index"
                  @click="handleFileClick(item)"
                  class="fileText"
                  >{{ item.name
                  }}<span
                    style="color: #000"
                    v-if="index + 1 !== row.suppFileInfoVos4.length"
                    >，</span
                  ></span
                >
                <!-- <span v-if="row.suppFileInfoVos7.length !== index">，</span> -->
              </template>
            </el-table-column>
            <el-table-column
              label="现场完成照片"
              prop="remarks"
              :show-overflow-tooltip="true"
              min-width="160"
            >
              <template #default="{ row }">
                <span
                  v-for="(item, index) in row.suppFileInfoVos5"
                  :key="index"
                  @click="handleFileClick(item)"
                  class="fileText"
                  >{{ item.name
                  }}<span
                    style="color: #000"
                    v-if="index + 1 !== row.suppFileInfoVos5.length"
                    >，</span
                  ></span
                >
                <!-- <span v-if="row.suppFileInfoVos7.length !== index">，</span> -->
              </template>
            </el-table-column>
            <el-table-column
              label="现场设备照片"
              prop="remarks"
              :show-overflow-tooltip="true"
              min-width="160"
            >
              <template #default="{ row }">
                <span
                  v-for="(item, index) in row.suppFileInfoVos6"
                  :key="index"
                  @click="handleFileClick(item)"
                  class="fileText"
                  >{{ item.name
                  }}<span
                    style="color: #000"
                    v-if="index + 1 !== row.suppFileInfoVos6.length"
                    >，</span
                  ></span
                >
                <!-- <span v-if="row.suppFileInfoVos7.length !== index">，</span> -->
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-collapse-item>
      <!-- 跟进记录 -->
      <el-collapse-item name="6" v-if="pageType === 'detail'">
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">变更记录</span>
        </template>
        <div class="follow-detail-info">
          <el-card style="margin: 0 0 20px 0; width: 100%">
            <template v-if="changeRecordList && changeRecordList.length > 0">
              <div
                v-for="(item, index) in changeRecordList"
                :key="index"
                style="margin-bottom: 10px"
              >
                <div>{{ item.createTime }}</div>
                <div>{{ item.content }}</div>
              </div>
            </template>
            <div v-else>暂无记录</div>
          </el-card>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script setup>
import Upload from "@/components/Upload/index";
import {
  getEndFollowApi,
  addFollowApi,
  getProjectApi,
} from "@/api/sales/project";
import { getArmedzoneDeviceApi } from "@/api/operation/flightdata.js";
import { getProvinceApi } from "@/api/information/customer";
// getUserListApi,
import { getDeptListApi } from "@/api/information/customer";
import { getUserListApi, workAllotApi } from "@/api/operation/work";
import {
  getDenfenseList,
  projectReturnTaskApi,
  projectSubmitTaskApi,
  projectExportTaskApi
} from "@/api/operation/project";
import {
  projectAllotTaskApi,
  projectEditAllotTaskApi,
  getUserTaskApi,
  projectTaskDetailApi,
  projectTaskSelfDetailApi,
  taskChangeDetailApi,
  projectFinishApi,
} from "@/api/operation/project";
import { getDictsApi } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
import { Base64 } from "js-base64";
import useUserStore from "@/store/modules/user";
//当前用户信息
const userStore = useUserStore();
const emit = defineEmits([
  // 刷新父组件表格数据
  "refreshList",
  // 更新跟进组件显隐
  "update:followAddShow",
]);
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
});
// 折叠栏默认展开
const activeNames = ref(["1", "2", "3", "4", "5", "6"]);
// 客户表单引用
const followFormRef = ref();
// 详情加载效果
const detailInfoShow = ref(false);
// 输入框引用
const refInput = ref();
// 当前选中用户
const currentUser = ref(null);
// 当前选中任务
const currentTask = ref(null);
// 任务列表
const taskList = ref([]);
// 项目下任务列表
const projectTaskList = ref([]);
// 变更记录
const changeRecordList = ref([]);
// 防区列表
const defenseList = ref([]);
// 设备列表
const deviceList = ref([]);
// 设备类型
const deviceTypeList = ref([]);
// 新增联系人表单显隐
const contactAddShow = ref(false);
// 联系人操作类型
const operateType = ref("");
// 新增销售列表表单显隐
const saleAddShow = ref(false);
// 联系人表单引用
const contactFormRef = ref();
// 销售表单引用
const saleFormRef = ref();
// 联系人当前索引(编辑联系人使用)
const tableIndex = ref(null);
// 销售清单当前索引(编辑销售清单使用)
const tableIndexSec = ref(null);
// 跟进表单引用
const followFormTemplate = {
  allotRelList: [], // 执行人
  endTime: "", // 	计划结束时间
  estimatedWorkHours: null, // 预估工时
  projectId: null, // 项目id
  remark: "", // 备注
  startTime: "", // 	计划开始时间
  taskType: null, // 	任务类型
  tableData: [],
  suppFileInfoVos: [],
  ywImplProInfoReqVos: [
    {
      suppFileInfoVos: [],
      suppFileInfoVos1: [], // 现场实地照片
      suppFileInfoVos2: [], // 外包用工合同
      suppFileInfoVos3: [], // 配件清单表
      suppFileInfoVos4: [], // 用电协议
      suppFileInfoVos5: [], // 现场完成照片
      suppFileInfoVos6: [], // 现场设备照片
      suppFileInfoVos7: [], // 物业租赁合同
    },
  ],
};
//文件校验规则
const fileValidate = (rule, value, callback) => {
  if (!followForm.value.ywImplProInfoReqVos[0].suppFileInfoVos.length) {
    callback(new Error("请上传交付文件"));
  } else {
    callback();
  }
};
const data = reactive({
  // 跟进表单
  followForm: JSON.parse(JSON.stringify(followFormTemplate)),
  // 联系人表单
  contactForm: {
    name: "",
    phone: "",
    practiceId: null,
    projectId: null,
    remarks: "",
  },
  // 销售清单表单
  saleForm: {
    actualHour: "", // 实际工时
    armedzoneId: null, // 防区id
    armedzoneName: "", // 防区中文
    cityId: null, // 市
    detailAdd: "", // 详细地址
    deviceModel: "", // 	设备型号
    deviceName: "", // 	设备名称
    deviceId:null,
    deviceType: null, // 	设备类型
    deviceTypeName: "", // 	设备类型中文
    deviceUuid: "", // 设备唯一id
    installType: "", // 	安装方式
    ipAddress: "", // IP地址
    manufacturer: "", // 	生产厂家
    pointAdd: "", // 点位地址
    policeOffice: "", // 所属派出所
    policeWay: "", // 民警联系方式
    projectTaskDetailId: null, // 明细id
    propertyName: "", // 物业名称
    propertyWay: "", // 物业联系方式
    provinceId: null, // 	省
    routBrand: "", // 路由器品牌型号
    simCard: "", // SIM卡信息
    suppFileInfoVos1: [], // 现场实地照片
    suppFileInfoVos2: [], // 外包用工合同
    suppFileInfoVos3: [], // 配件清单表
    suppFileInfoVos4: [], // 用电协议
    suppFileInfoVos5: [], // 现场完成照片
    suppFileInfoVos6: [], // 现场设备照片
    suppFileInfoVos7: [], // 物业租赁合同
    zoneId: null, // 区
  },
  // 跟进表单校验规则
  queryRules: {
    actualHour: [
      { required: true, message: "请输入实际工时", trigger: "blur" },
    ],
    suppFileInfoVos: [
      {
        required: true,
        validator: fileValidate,
        message: "请上传交付文件",
        trigger: "change",
      },
    ],
  },
  // 联系人表单校验规则
  queryContactRules: {
    actualHour: [
      { required: true, message: "请输入实时工时", trigger: "blur" },
    ],
    deviceId: [
      { required: true, message: "请选择设备名称", trigger: "blur" },
    ],
    deviceModel: [
      { required: true, message: "请输入设备型号", trigger: "blur" },
    ],
    manufacturer: [
      { required: true, message: "请输入生产厂家", trigger: "blur" },
    ],
    installType: [
      { required: true, message: "请输入安装方式", trigger: "blur" },
    ],
    deviceUuid: [{ required: true, message: "请输入设备ID", trigger: "blur" }],
    simCard: [{ required: true, message: "请输入SIM卡信息", trigger: "blur" }],
    routBrand: [
      { required: true, message: "请输入路由器品牌型号", trigger: "blur" },
    ],
    ipAddress: [{ required: true, message: "请输入IP地址", trigger: "blur" }],

    armedzoneId: [
      { required: true, message: "请选择选择防区", trigger: "change" },
    ],
    deviceType: [
      { required: true, message: "请选择设备类型", trigger: "change" },
    ],

    suppFileInfoVos3: [
      { required: true, message: "请上传配件清单表", trigger: "change" },
    ],
    suppFileInfoVos4: [
      { required: true, message: "请上传用电协议", trigger: "change" },
    ],
    suppFileInfoVos5: [
      { required: true, message: "请上传现场完成照片", trigger: "change" },
    ],
    suppFileInfoVos6: [
      { required: true, message: "请上传现场设备照片", trigger: "change" },
    ],
  },
  // 销售清单表单校验规则
  querySaleRules: {
    actualHour: [
      { required: true, message: "请输入实时工时", trigger: "blur" },
    ],
    propertyName: [
      { required: true, message: "请输入物业名称", trigger: "blur" },
    ],
    policeOffice: [
      { required: true, message: "请输入所属派出所", trigger: "blur" },
    ],
    propertyWay: [
      { required: true, message: "请输入物业联系方式", trigger: "blur" },
    ],
    policeWay: [
      { required: true, message: "请输入民警联系方式", trigger: "blur" },
    ],
    pointAdd: [{ required: true, message: "请输入点位名称", trigger: "blur" }],
    detailAdd: [{ required: true, message: "请输入详细地址", trigger: "blur" }],
    cityId: [{ required: true, message: "请选择省市区", trigger: "change" }],
  },
  // 用户列表
  userList: [],
  // 部门列表
  deptList: [],
  // 省列表
  provinceList: [],
  // 市列表
  cityList: [],
  // 区列表
  areaList: [],
});
const {
  contactForm,
  saleForm,
  followForm,
  queryRules,
  userList,
  deptList,
  queryContactRules,
  querySaleRules,
  provinceList,
  cityList,
  areaList,
} = toRefs(data);

/**
 * @description: 处理文件点击
 * @param {Object} item 文件信息
 */
const handleFileClick = (item) => {
  let docUrl = item.url;
  let officeUrl =
    "http://101.71.158.60:50098/onlinePreview?url=" +
    encodeURIComponent(Base64.encode(docUrl)) +
    "&watermarkTxt=" +
    encodeURIComponent(userStore.nickName); // 在新窗口打开编码后的链接
  window.open(officeUrl, "_target");
};

/**
 * @description: 处理任务操作
 * @param {Number} type 1.退回 2.开始 3.提交
 */
const handleTaskOperate = async (type, followFormRef) => {
  switch (type) {
    // 退回
    case 1:
      ElMessageBox.prompt("退回原因：", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPlaceholder: "请输入",
        inputPattern: /\S/,
        inputErrorMessage: "请输入退回原因",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async ({ value }) => {
          const arr = {
            projectId: followForm.value.projectId, // 项目id
            projectTaskId: followForm.value.projectTaskId, // 任务id
            returnReasons: value, // 退回原因
          };
          const res = await projectReturnTaskApi(arr);
          if (res.code === 200) {
            ElMessage.success(res.msg);
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;
    // 开始
    case 2:
      ElMessageBox.confirm("此操作将开始当前任务，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
        type: "warning",
      })
        .then(async () => {
          followForm.value.type = 0;
          followForm.value.ywImplProInfoReqVos.forEach((item) => {
            // ];
            if (![0, 2, 3, 5, 6, 7].includes(currentTask.value)) {
              item.suppFileInfoVos = [
                ...(item.suppFileInfoVos1 ? item.suppFileInfoVos1 : []),
                ...(item.suppFileInfoVos2 ? item.suppFileInfoVos2 : []),
                ...(item.suppFileInfoVos3 ? item.suppFileInfoVos3 : []),
                ...(item.suppFileInfoVos4 ? item.suppFileInfoVos4 : []),
                ...(item.suppFileInfoVos5 ? item.suppFileInfoVos5 : []),
                ...(item.suppFileInfoVos6 ? item.suppFileInfoVos6 : []),
                ...(item.suppFileInfoVos7 ? item.suppFileInfoVos7 : []),
              ];
            }
          });
          const res = await projectSubmitTaskApi(followForm.value);
          if (res.code === 200) {
            // emit("update:followAddShow", false);
            // emit("refreshList", false);
            ElMessage.success(res.msg);
            followForm.value.taskImplStatusName = "进行中";
            setTimeout(async () => {
              const res = await projectTaskSelfDetailApi(
                followForm.value.projectId
              );
              projectTaskList.value = res;
            }, 2000);
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;
    // 提交
    case 3:
      if (
        currentTask.value === 1 &&
        !followForm.value.ywImplProInfoReqVos.length
      ) {
        // 现场勘测
        return ElMessage.warning("请添加现场勘察任务明细!");
      }
      if (
        currentTask.value === 4 &&
        !followForm.value.ywImplProInfoReqVos.length
      ) {
        // 现场安装
        return ElMessage.warning("请添加现场安装/调试任务明细!");
      }
      await followFormRef.validate(async (valid, fields) => {
        if (valid) {
          ElMessageBox.confirm("此操作将完成当前任务，是否继续？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            confirmButtonClass: "confirmBtnClass",
            cancelButtonClass: "cancelBtnClass",
            type: "warning",
          })
            .then(async () => {
              followForm.value.type = 1;
              followForm.value.ywImplProInfoReqVos.forEach((item) => {
                // ];
                if (![0, 2, 3, 5, 6, 7].includes(currentTask.value)) {
                  item.suppFileInfoVos = [
                    ...(item.suppFileInfoVos1 ? item.suppFileInfoVos1 : []),
                    ...(item.suppFileInfoVos2 ? item.suppFileInfoVos2 : []),
                    ...(item.suppFileInfoVos3 ? item.suppFileInfoVos3 : []),
                    ...(item.suppFileInfoVos4 ? item.suppFileInfoVos4 : []),
                    ...(item.suppFileInfoVos5 ? item.suppFileInfoVos5 : []),
                    ...(item.suppFileInfoVos6 ? item.suppFileInfoVos6 : []),
                    ...(item.suppFileInfoVos7 ? item.suppFileInfoVos7 : []),
                  ];
                }
              });
              const res = await projectExportTaskApi(followForm.value);
              if (res.code === 200) {
                // emit("update:followAddShow", false);
                // emit("refreshList", false);
                followForm.value.taskImplStatusName = "已完成";
                ElMessage.success(res.msg);
                setTimeout(async () => {
                  const res = await projectTaskSelfDetailApi(
                    followForm.value.projectId
                  );
                  projectTaskList.value = res;
                }, 2000);
              } else {
                ElMessage.error(res.msg);
              }
            })
            .catch(() => {});
        }
      });
      break;
    default:
      break;
  }
};

/**
 * @description: 处理销售清单表格操作
 * @param {String} type 操作类型
 * @param {Object} row  当前行数据
 * @param {Number} tabIndex 表格当前索引
 */
const handleOperateSec = (type, row, tabIndex) => {
  if (type === "edit") {
    tableIndexSec.value = tabIndex;
    saleForm.value = JSON.parse(JSON.stringify(row));
    saleAddShow.value = true;
    operateType.value = "edit";
    nextTick(() => {
      refSelect.value.focus(); // 聚焦
    });
  } else {
    followForm.value.ywImplProInfoReqVos.splice(tabIndex, 1);
  }
};

/**
 * @description: 处理联系人表格操作
 * @param {String} type 操作类型
 * @param {Object} row  当前行数据
 * @param {Number} tabIndex 表格当前索引
 */
const handleOperate = (type, row, tabIndex) => {
  if (type === "edit") {
    tableIndex.value = tabIndex;
    contactForm.value = JSON.parse(JSON.stringify(row));
    contactAddShow.value = true;
    operateType.value = "edit";
    nextTick(() => {
      // contactRefInput.value.focus(); // 聚焦
    });
  } else {
    followForm.value.ywImplProInfoReqVos.splice(tabIndex, 1);
  }
};

/**
 * @description: 新增、编辑联系人
 * @param {Object} contactFormRef 联系人表单引用
 */
const handleContactAdd = async (contactFormRef) => {
  if (!contactFormRef) return;
  await contactFormRef.validate(async (valid, fields) => {
    if (valid) {
      if (operateType.value === "edit") {
        followForm.value.ywImplProInfoReqVos[tableIndex.value] = JSON.parse(
          JSON.stringify(saleForm.value)
        );
      } else {
        followForm.value.ywImplProInfoReqVos.push(
          JSON.parse(JSON.stringify({ ...saleForm.value }))
        );
      }
      contactForm.value = {
        name: "",
        phone: "",
        practiceId: null,
        projectId: null,
        remarks: "",
      };
      //   contactAddShow.value = false;
      contactFormRef.resetFields();
      nextTick(() => {
        // contactRefInput.value.focus(); // 聚焦
      });
    } else {
      console.log("error submit!");
    }
  });
  //   operateType.value = "";
};

/**
 * @description: 新增、编辑销售清单
 * @param {Object} saleFormRef 联售清单引用
 */
const handleSaleAdd = async (saleFormRef) => {
  if (!saleFormRef) return;
  await saleFormRef.validate(async (valid, fields) => {
    if (valid) {
      if (operateType.value === "edit") {
        followForm.value.ywImplProInfoReqVos[tableIndexSec.value] = JSON.parse(
          JSON.stringify(saleForm.value)
        );
      } else {
        followForm.value.ywImplProInfoReqVos.push(
          JSON.parse(JSON.stringify({ ...saleForm.value }))
        );
      }
      saleForm.value = {
        actualHour: "", // 实际工时
        armedzoneId: null, // 防区id
        armedzoneName: "", // 防区中文
        cityId: null, // 市
        detailAdd: "", // 详细地址
        deviceModel: "", // 	设备型号
        deviceName: "", // 	设备名称
        deviceType: null, // 	设备类型
        deviceTypeName: "", // 	设备类型中文
        deviceUuid: "", // 设备唯一id
        installType: "", // 	安装方式
        ipAddress: "", // IP地址
        manufacturer: "", // 	生产厂家
        pointAdd: "", // 点位地址
        policeOffice: "", // 所属派出所
        policeWay: "", // 民警联系方式
        projectTaskDetailId: null, // 明细id
        propertyName: "", // 物业名称
        propertyWay: "", // 物业联系方式
        provinceId: null, // 	省
        routBrand: "", // 路由器品牌型号
        simCard: "", // SIM卡信息
        suppFileInfoVos1: [], // 现场实地照片
        suppFileInfoVos2: [], // 外包用工合同
        suppFileInfoVos3: [], // 配件清单表
        suppFileInfoVos4: [], // 用电协议
        suppFileInfoVos5: [], // 现场完成照片
        suppFileInfoVos6: [], // 现场设备照片
        suppFileInfoVos7: [], // 物业租赁合同
        zoneId: null, // 区
      };
      //   contactAddShow.value = false;
      saleFormRef.resetFields();
      nextTick(() => {
        refSelect.value.focus(); // 聚焦
      });
    } else {
      console.log("error submit!");
    }
  });
  //   operateType.value = "";
};

/**
 * @description: 处理联系人操作
 */
const handleContactOperate = () => {
  contactAddShow.value = true;
  operateType.value = "add";
  nextTick(() => {
    // contactRefInput.value.focus(); // 聚焦
  });
};

/**
 * @description: 处理销售清单操作
 */
const handleSaleOperate = () => {
  saleAddShow.value = true;
  operateType.value = "add";
  nextTick(() => {
    refSelect.value.focus(); // 聚焦
  });
};

/**
 * @description: 联系人返回
 */
const handleProjectBack = () => {
  contactAddShow.value = false;
  nextTick(() => {
    refInput.value.focus(); // 聚焦
  });
};

/**
 * @description: 处理省市区操作
 * @param {String} type 类型
 */
const handleProvince = (type, value) => {
  switch (type) {
    case "province":
      cityList.value = [];
      areaList.value = [];
      saleForm.value.cityId = null;
      saleForm.value.zoneId = null;
      getProvinceApi(saleForm.value.provinceId).then((res) => {
        if (res.code === 200) {
          cityList.value = res.data;
        }
      });
      provinceList.value.forEach((item) => {
        if (item.value === value) {
          saleForm.value.provinceName = item.label;
        }
      });
      break;
    case "city":
      areaList.value = [];
      saleForm.value.area = null;
      getProvinceApi(saleForm.value.cityId).then((res) => {
        if (res.code === 200) {
          areaList.value = res.data;
        }
      });
      cityList.value.forEach((item) => {
        if (item.value === value) {
          saleForm.value.cityName = item.label;
        }
      });
      break;
    case "area":
      areaList.value.forEach((item) => {
        if (item.value === value) {
          saleForm.value.zoneName = item.label;
        }
      });
      break;
  }
};

/**
 * @description: 销售清单返回
 */
const handleSaleBack = () => {
  saleAddShow.value = false;
  nextTick(() => {
    refInput.value.focus(); // 聚焦
  });
};

/**
 * @description: 保存
 * @param {Object} followFormRef 跟进表单引用
 */
const handleAddSave = async (followFormRef) => {
  if (!followFormRef) return;
  await followFormRef.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          let res;
          if (followForm.value.projectTaskId) {
            res = await projectEditAllotTaskApi(followForm.value);
          } else {
            res = await projectAllotTaskApi(followForm.value);
          }
          if (res.code === 200) {
            ElMessage.success(res.msg);
            // followForm.value = JSON.parse(JSON.stringify(followFormTemplate));
            const result = await projectTaskDetailApi(
              followForm.value.projectId
            );
            projectTaskList.value = result;
            taskList.value.forEach((item) => {
              projectTaskList.value.forEach((proItem) => {
                if (item.value === proItem.taskType) {
                  item.type = "已分配";
                }
              });
            });
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
    }
  });
};

/**
 * @description: 完结
 * @param {Object} followFormRef 跟进表单引用
 */
const handleEndOperation = async () => {
  ElMessageBox.confirm("确定完结此项目吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "confirmBtnClass",
    cancelButtonClass: "cancelBtnClass",
  })
    .then(async () => {
      let res = await projectFinishApi(followForm.value.projectId);
      if (res.code === 200) {
        emit("update:followAddShow", false);
        emit("refreshList", false);
        ElMessage.success(res.msg);
        followForm.value = JSON.parse(JSON.stringify(followFormTemplate));
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {});
};

/**
 * @description: 匹配工程师名称
 */
const getNameById = (id) => {
  const foundItem = userList.value.find((item) => item.userId === id);
  return foundItem ? foundItem.nickName : "未知";
};

/**
 * @description: 获取用户名下任务
 */
const handleUserTask = async (userId) => {
  currentUser.value = userId;
  const res = await getUserTaskApi(userId);
  followForm.value.tableData = res.proTaskListVos;
};

/**
 * @description: 文件上传成功处理
 * @param {Object} response 文件信息
 */
function uploadSuccess(response, type) {
  switch (currentTask.value) {
    case 0:
      // 项目启动会
      followForm.value.ywImplProInfoReqVos[0].suppFileInfoVos.push({
        ...response,
        businessType: 17,
        erpTaskType: 0,
      });
      break;
    case 1:
      // 现场勘察
      saleForm.value[`suppFileInfoVos${type}`].push({
        ...response,
        businessType: 18,
        erpTaskType: type,
      });
      break;
    case 2:
      // 制定项目方案
      followForm.value.ywImplProInfoReqVos[0].suppFileInfoVos.push({
        ...response,
        businessType: 17,
        erpTaskType: 0,
      });
      break;
    case 3:
      // 配件/设备出库
      followForm.value.ywImplProInfoReqVos[0].suppFileInfoVos.push({
        ...response,
        businessType: 17,
        erpTaskType: 0,
      });
      break;
    case 4:
      saleForm.value[`suppFileInfoVos${type}`].push({
        ...response,
        businessType: 19,
        erpTaskType: type,
      });
      break;
    case 5:
      // 设备到货清单-销售
      followForm.value.ywImplProInfoReqVos[0].suppFileInfoVos.push({
        ...response,
        businessType: 17,
        erpTaskType: 0,
      });
      break;
    case 6:
      // 飞行验收
      followForm.value.ywImplProInfoReqVos[0].suppFileInfoVos.push({
        ...response,
        businessType: 17,
        erpTaskType: 0,
      });
      break;
    case 7:
      // 项目验收
      followForm.value.ywImplProInfoReqVos[0].suppFileInfoVos.push({
        ...response,
        businessType: 17,
        erpTaskType: 0,
      });
      break;
    default:
      break;
  }
}

/**
 * @description: 删除文件
 * @param {Number} index 当前文件索引
 */
function uploadRemove(index, type) {
  switch (currentTask.value) {
    case 0:
      // 项目启动会
      followForm.value.ywImplProInfoReqVos[0].suppFileInfoVos.splice(index, 1);
      break;
    case 1:
      // 现场勘察
      saleForm.value[`suppFileInfoVos${type}`].splice(index, 1);
      break;
    case 2:
      // 制定项目方案
      followForm.value.ywImplProInfoReqVos[0].suppFileInfoVos.splice(index, 1);
      break;
    case 3:
      // 配件/设备出库
      followForm.value.ywImplProInfoReqVos[0].suppFileInfoVos.splice(index, 1);
      break;
    case 4:
      saleForm.value[`suppFileInfoVos${type}`].splice(index, 1);
      break;
    case 5:
      // 设备到货清单-销售
      followForm.value.ywImplProInfoReqVos[0].suppFileInfoVos.splice(index, 1);
      break;
    case 6:
      // 飞行验收
      followForm.value.ywImplProInfoReqVos[0].suppFileInfoVos.splice(index, 1);
      break;
    case 7:
      // 项目验收
      followForm.value.ywImplProInfoReqVos[0].suppFileInfoVos.splice(index, 1);
      break;
    default:
      break;
  }
}

/**
 * @description: 处理任务点击
 */
const handleTaskClick = async (item) => {
  // if (item.type !== "已分配") {
  //   return ElMessage.warning("该任务未分配！");
  // }
  // if (item.value === 5) {
  //   return ElMessage.warning("待开发");
  // }
  followForm.value.taskImplStatusName = "待执行";
  followForm.value = {
    ...JSON.parse(JSON.stringify(followFormTemplate)),
    projectId: followForm.value.projectId,
  };
  saleAddShow.value = false;
  contactAddShow.value = false;
  changeRecordList.value = [];
  followForm.value.allotRelList = [];
  followForm.value.startTime = "";
  followForm.value.endTime = "";
  followForm.value.projectTaskId = null;
  followForm.value.remark = "";
  followForm.value.estimatedWorkHours = "";
  currentTask.value = item.value;
  followForm.value.taskType = item.value;
  if (item.value == 1 || item.value == 4) {
    followForm.value.ywImplProInfoReqVos = [];
  } else {
    followForm.value.ywImplProInfoReqVos = [
      {
        suppFileInfoVos: [],
      },
    ];
  }
  projectTaskList.value.forEach(async (taskItem) => {
    // 匹配当前任务
    if (taskItem.taskType === item.value) {
      followForm.value.allotRelList = taskItem.executorNums;
      followForm.value.startTime = taskItem.startTime;
      followForm.value.endTime = taskItem.endTime;
      followForm.value.projectTaskId = taskItem.projectTaskId;
      followForm.value.remark = taskItem.remark;
      followForm.value.estimatedWorkHours = taskItem.estimatedWorkHours;
      followForm.value.proTaskName = taskItem.proTaskName;
      followForm.value.createTime = taskItem.createTime;
      followForm.value.startTimeNum = taskItem.startTimeNum;
      followForm.value.endTimeNum = taskItem.endTimeNum;
      followForm.value.actualHour = taskItem.actualHour;
      followForm.value.taskImplStatusName = taskItem.taskImplStatusName;
      if (props.pageType == "detail") {
        followForm.value = { ...followForm.value, ...taskItem };
      }
      if (taskItem.ywProjectTaskDetailInfoRespVos.length) {
        // 无明细
        if ([0, 2, 3, 5, 6, 7].includes(currentTask.value)) {
          // return
          followForm.value.ywImplProInfoReqVos[0].suppFileInfoVos =
            taskItem.ywProjectTaskDetailInfoRespVos[0].fileGroupInfoVos[0].info;
        } else {
          // 有明细groupItem
          followForm.value.ywImplProInfoReqVos =
            taskItem.ywProjectTaskDetailInfoRespVos;
          followForm.value.ywImplProInfoReqVos.forEach((followItem) => {
            // followItem[`suppFileInfoVos${groupItem.type}`] = []
            followItem.fileGroupInfoVos.forEach((groupItem) => {
              followItem[`suppFileInfoVos${groupItem.type}`] = groupItem.info;
            });
          });
        }
      }
      handleDepart(taskItem.deptId, false);
      if (props.pageType === "detail") {
        const res = await taskChangeDetailApi(taskItem.projectTaskId);
        changeRecordList.value = res;
      }
    }
  });
  if(!followForm.value.taskImplStatusName) {
    followForm.value.taskImplStatusName = '进行中';
  }
};

/**
 * @description: 工程师变更
 */
const handleAllotRelChange = async (userId) => {
  if (
    !followForm.value.allotRelList.some((item) => currentUser.value === item)
  ) {
    followForm.value.tableData = [];
    currentUser.value = null;
  }
};

/**
 * @description: 处理防区变更
 */
const handleDefenseChange = async (value) => {
  saleForm.value.deviceId = null;
  saleForm.value.deviceModel = "";
    saleForm.value.deviceType = null;
    saleForm.value.manufacturer = "";
    saleForm.value.installType = "";
    saleForm.value.deviceUuid = "";
    saleForm.value.simCard = "";
    saleForm.value.ipAddress = "";
    saleForm.value.deviceName = "";
    saleForm.value.deviceTypeName = "";
  getArmedzoneDevice();
  if (value) {
    defenseList.value.forEach((item) => {
      if (item.id === value) {
        saleForm.value.armedzoneName = item.armedzoneName;
      }
    });
  } else {
    saleForm.value.armedzoneName = "";
  }
};

/**
 * @description: 处理设备变更
 */
const handleDeviceChange = async (value) => {
  if (value) {
    deviceList.value.forEach((item) => {
      if (item.id === value) {
        console.log("处理设备变更");
        console.log(item);
        saleForm.value.deviceModel = item.model;
        saleForm.value.deviceType = item.deviceTypeId;
        saleForm.value.deviceTypeName = item.deviceType;
        saleForm.value.manufacturer = item.brand;
        saleForm.value.installType = item.installType;
        saleForm.value.deviceUuid = item.deviceUuid;
        saleForm.value.simCard = item.simInfo;
        saleForm.value.ipAddress = item.ipaddress;
        saleForm.value.deviceName = item.armedzoneName;
      }
    });
  } else {
    saleForm.value.deviceModel = "";
    saleForm.value.deviceType = null;
    saleForm.value.manufacturer = "";
    saleForm.value.installType = "";
    saleForm.value.deviceUuid = "";
    saleForm.value.simCard = "";
    saleForm.value.ipAddress = "";
    saleForm.value.deviceName = "";
    saleForm.value.deviceTypeName = "";
  }
};

/**
 * @description: 处理设备变更
 */
const handledeviceTypeChange = async (value) => {
  if (value) {
    deviceTypeList.value.forEach((item) => {
      if (item.value === value) {
        saleForm.value.deviceTypeName = item.label;
      }
    });
  } else {
    saleForm.value.deviceTypeName = "";
  }
};

/**
 * @description: 返回
 */
const handleBack = () => {
  ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "confirmBtnClass",
    cancelButtonClass: "cancelBtnClass",
  })
    .then(async () => {
      emit("update:followAddShow", false);
      followForm.value = JSON.parse(JSON.stringify(followFormTemplate));
    })
    .catch(() => {});
};

/**
 * @description: 处理部门选择
 * @param {Number} value 当前值
 */
 const handleDepart = async (value, flag = true) => {
    await getUserListApi(2).then((res) => {
      if (res) {
        userList.value = res;
      }
    });
};

/**
 * @description: 处理详情信息
 * @param {Number} id
 */
 const handleDetailInfo = async (row) => {
  detailInfoShow.value = true
  await getDict();
  const id = row.projectId;
  // followForm.value.startTime = row.desireStartTime;
  // followForm.value.endTime = row.desireEndTime;
  // followForm.value.workOrderId = row.workOrderId;
  // followForm.value.maintanceTaskName = row.workOrderName;
  try {
    followForm.value.projectId = id;
    const res = await projectTaskSelfDetailApi(id);
    projectTaskList.value = res;
    let allotTask = []
    taskList.value.forEach((item) => {
      item.type = "已分配"
      projectTaskList.value.forEach((proItem,index) => {
        if (item.value === proItem.taskType) {
          item.type = "已分配";
        }
      });
      allotTask.push(item)
    });
    taskList.value = allotTask
    setTimeout(() => {
      // 首次进入回显
      handleTaskClick(taskList.value[0])
      detailInfoShow.value = false
    }, 500);
  } catch (error) {}
};

// 设备列表
const getArmedzoneDevice = () => {
  if (saleForm.value.armedzoneId) {
    getArmedzoneDeviceApi(saleForm.value.armedzoneId).then((res) => {
      deviceList.value = res;
    });
  } else {
    deviceList.value = [];
  }
};

/**
 * @description: 字典列表
 */
const getDict = async () => {
  await getDeptListApi(107).then((res) => {
    if (res.code === 200) {
      deptList.value = res.data;
    }
  });
  await getDictsApi("erp_task_type").then((res) => {
    // 任务列表
    if (res.code === 200) {
      taskList.value = res.data;
      taskList.value.forEach((item) => {
        item.type = "未分配";
      });
    }
  });

  await getDictsApi("erp_device_type").then((res) => {
    // 设备类型
    if (res.code === 200) {
      deviceTypeList.value = res.data;
    }
  });
  // 省
  await getProvinceApi(1).then((res) => {
    if (res.code === 200) {
      provinceList.value = res.data;
    }
  });
  // 防区
  await getDenfenseList().then((res) => {
    if (res) {
      defenseList.value = res;
    }
  });
};

onMounted(() => {
  handleDepart();
  if (props.pageType !== "detail" && props.pageType !== "check") {
    nextTick(() => {
      setTimeout(() => {
        refInput.value.focus();
      }, 800);
    });
  }
});

defineExpose({
  handleDetailInfo,
});
</script>
<style lang="scss" scoped>
.followAdd {
  padding: 20px;
  width: 100%;
  height: 100%;
  .follow-info {
    padding: 20px 10px 5px 10px;
    background-color: #f0f0f0;
    margin: 10px 0;
  }
  .follow-detail-info {
    margin-top: 20px;
  }
  .task-box {
    width: 100%;
    background-color: #f8faff;
  }
  .contact-info {
    padding-top: 20px;
  }
  .task {
    width: 1360px;
    height: 50px;
    margin-bottom: 20px;
    display: flex;
    // overflow-x: auto;
    &-item {
      background-color: #dee6ed;
      min-width: 180px;
      height: 50px;
      line-height: 50px;
      text-align: center;
      margin-right: 2px;
      cursor: pointer;
      &:hover {
        // background: #007cef;
        // color: #fff;
      }
      background: #dee6ed;
      color: #333333;
    }
    .task-current {
      background: #007cef;
      color: #fff;
    }
  }
  .people {
    margin-top: 10px;
    &-item {
      margin-right: 10px;
      cursor: pointer;
      text-decoration: underline;
      &:hover {
        color: #007cef;
      }
    }
  }
  .task-number {
    margin-top: 10px;
  }
  .footer-button {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    padding-bottom: 20px;
  }
  .fileText {
    color: #6597fe;
    cursor: pointer;
  }
}
</style>
